package www.xudan.android_ffmpeg.videoplayer.util;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import www.xudan.android_ffmpeg.videoplayer.widget.BasePlayerView;

public class AnimUtil {
    ValueAnimator animator;
    AnimListener listener;
    static Map<BasePlayerView, List<AnimUtil>> map = new HashMap<>();
    BasePlayerView basePlayerView;

    public static AnimUtil createAnimUtil(BasePlayerView basePlayerView, float start, float end, long duration, AnimListener listener) {
        AnimUtil animUtil = new AnimUtil();
        animUtil.listener = listener;
        animUtil.basePlayerView = basePlayerView;
        animUtil.animator = ValueAnimator.ofFloat(start, end).setDuration(duration);
        List<AnimUtil> animUtils = map.get(basePlayerView);
        animUtils = animUtils == null ? new ArrayList<AnimUtil>() : animUtils;
        animUtils.add(animUtil);
        map.put(basePlayerView, animUtils);
        return animUtil;
    }

    public interface AnimListener {
        void animUpdate(float value, int status);
    }

    public void start() {
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                listener.animUpdate(value, -1);
            }
        });
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                listener.animUpdate(0, 1);
                List<AnimUtil> animUtils = map.get(basePlayerView);
                if (animUtils != null) {
                    animUtils.remove(AnimUtil.this);
                }
                animator = null;
                listener = null;
            }
        });
        animator.start();
    }

    //释放动画资源 防止内存泄漏
    public static void release(BasePlayerView playerView) {
        List<AnimUtil> animUtils = map.get(playerView);
        if (animUtils != null) {
            for (AnimUtil animUtil : animUtils) {
                if (animUtil.animator != null) {
                    animUtil.animator.cancel();
                }
                animUtil.animator = null;
                animUtil.listener = null;
            }
        }
        map.remove(playerView);
    }
}
